package com.daodao.daodaoschedule.application.service.jobhandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daodao.daodaoschedule.application.service.RemindEventService;
import com.daodao.daodaoschedule.application.service.WechatAccountService;
import com.daodao.daodaoschedule.application.service.WechatMemberService;
import com.daodao.daodaoschedule.application.service.WechatMessageSendService;
import com.daodao.daodaoschedule.domain.wechat.WechatAccount;
import com.daodao.daodaoschedule.domain.wechat.WechatMember;
import com.daodao.daodaoschedule.infrastructure.constant.WechatMessageTypeEnum;
import com.daodao.daodaoschedule.infrastructure.dao.entity.WechatAccountPO;
import com.daodao.daodaoschedule.infrastructure.dao.entity.WechatMemberPO;
import com.daodao.daodaoschedule.infrastructure.util.BeanCopyUtils;
import com.daodao.daodaoschedule.infrastructure.util.JacksonUtil;
import com.daodao.daodaoschedule.infrastructure.util.StringUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.kevinsawicki.http.HttpRequest;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mal
 * @date 2022-09-02 16:46
 */
@Component
public class BabeWeekJob {


    @Autowired
    WechatAccountService wechatAccountService;

    @Autowired
    WechatMemberService wechatMemberService;


    @Autowired
    WechatMessageSendService wechatMessageSendService;

    @Autowired
    RemindEventService remindEventService;
    private static final Logger logger = LoggerFactory.getLogger(BabeWeekJob.class);

    public static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    public static final String MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    public static final String DATA_FORMATE = "{\"aa\":{\"value\":\"${weeks}\",\"color\":\"#173177\"},\"bb\":{\"value\":\"${days}\",\"color\":\"#173177\"}}";


    @XxlJob("weekJobHandler")
    public void weekJobHandler() throws Exception {
        logger.info("weekJobHandler start");

        XxlJobHelper.log("XXL-JOB, weekJobHandler");
        LocalDate originDate = LocalDate.of(2022, 4, 9);
        LocalDate now = LocalDate.now();
        long between = now.toEpochDay() - originDate.toEpochDay();
        long week = between / 7;
        long additional = between % 7;

        List<WechatAccountPO> allValid = wechatAccountService.getAllValid();
        if (allValid.isEmpty()) {
            XxlJobHelper.log("weekJobHandler ,cannot find WechatAccount");
            logger.error("weekJobHandler ,cannot find WechatAccount");

            return;
        }
        WechatAccountPO wechatAccountPO = allValid.get(0);

        String url = TOKEN_URL + "?grant_type=client_credential&appid=" + wechatAccountPO.getAppId()
                + "&secret=" + wechatAccountPO.getAppSecret();

        HttpRequest request = HttpRequest
                .get(url)
                .connectTimeout(5000)
                .readTimeout(10000)
                .acceptGzipEncoding().uncompress(true);

        if (request.ok()) {
            String body = request.body();
            logger.info("获取的token信息为:{}", body);
            TokenResponse tokenResponse = JacksonUtil.readJson2Object(body, TokenResponse.class);
            Map<String, Object> templateMap = new HashMap<>();
            templateMap.put("weeks", week);
            templateMap.put("days", additional);
            String dataStr = StringUtil.formatTemplate(DATA_FORMATE, templateMap);

            List<WechatMember> wechatMemberPOS = wechatMemberService.getMemberList(
                    wechatAccountPO.getId());

            if (wechatMemberPOS.isEmpty()) {
                logger.error("accountId 【{}】 has not wechat members", wechatAccountPO.getId());
            }
            for (WechatMember wechatMemberPO : wechatMemberPOS) {

                Map<String, Object> sendMap = new HashMap<>();
                sendMap.put("touser", wechatMemberPO.getOpenId());
                sendMap.put("template_id", "oMRnYyk4rVzJ99kO_pHwF4F6xPZTLOPJYfHdjq-93lA");
                sendMap.put("data", JacksonUtil.readJson2Object(dataStr, Map.class));
                sendMap.put("topcolor", "#FF0000");

                HttpRequest messageRequest = HttpRequest
                        .get(MESSAGE_URL + tokenResponse.getAccessToken())
                        .connectTimeout(5000)
                        .readTimeout(10000)
                        .acceptGzipEncoding().uncompress(true)
                        .send(JacksonUtil.writeObj2Json(sendMap));

                logger.info(messageRequest.body());
            }


        } else {
            logger.info("获取token信息出错" + request.body());

        }


    }


    @Data
    public static class TokenResponse {

        @JsonProperty("access_token")
        private String accessToken;

        @JsonProperty("expires_in")
        private Integer expiresIn;


    }


    @XxlJob("birthJobHandler")
    public void birthJobHandler() throws Exception {
        logger.info("birthJobHandler start");

        LocalDate originDate = LocalDate.of(2023, 1, 19);
        LocalDate now = LocalDate.now();
        long between = now.toEpochDay() - originDate.toEpochDay();

        Map<String, Object> templateMap = new HashMap<>();
        templateMap.put("days", between + 1);
        templateMap.put("remind", remindEventService.buildRemindInfo());

        WechatAccount wechatAccount = wechatAccountService.getByAccountId(null);
        if (wechatAccount == null) {
            return;
        }

        List<WechatMember> wechatMembers = wechatMemberService.getMemberList(wechatAccount.getId());
        if (wechatMembers.isEmpty()) {
            logger.error("accountId 【{}】 has not wechat members", wechatAccount.getId());
            return;
        }
        for (WechatMember wechatMember : wechatMembers) {

            wechatMessageSendService.sendMessage(wechatMember.getOpenId(), WechatMessageTypeEnum.BIRTH, wechatAccount.getId(), templateMap);

        }

    }








}
